package com.bank.java.agent;

import javassist.*;

import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.security.ProtectionDomain;

public class OrderServiceImplTransformer implements ClassFileTransformer {
    public final String injectedClassName1 = "com.bank.study.pojo.Product";
    public final String injectedClassName2 = "com.bank.study.service.impl.OrderServiceImpl";
    public final String methodName1 = "setProductName";
    public final String methodName2 = "selectProductList";
    @Override
    public byte[] transform(ClassLoader loader, String className,
                            Class<?> classBeingRedefined, ProtectionDomain protectionDomain,
                            byte[] classfileBuffer) throws IllegalClassFormatException {
        className = className.replace("/", ".");
        System.out.println( "class: " + className);
        ClassPool pool = ClassPool.getDefault();// 使用全称,用于取得字节码类<使用javassist>
        //将额外的类路径注册到ClassPool中
        ClassClassPath classPath = new ClassClassPath(this.getClass());
        pool.insertClassPath(classPath);
        CtClass ctclass = null;
        if (className.equals(injectedClassName1)) {
            try {
                ctclass = pool.get(className);
                CtMethod ctmethod1 = ctclass.getDeclaredMethod(methodName1);// 得到这方法实例
                ctmethod1.insertAfter(" \n this.productName = productName + \"abc\";\n"+
                        "System.out.println(222333);");
                System.out.println( "444444444444444444");
                return ctclass.toBytecode();
            } catch (Exception e) {
                System.out.println(e.getMessage());
                e.printStackTrace();
            }
        }else if (className.equals(injectedClassName2)){
            try {
                ctclass = pool.get(className);
                CtMethod ctmethod2 = ctclass.getDeclaredMethod(methodName2);// 得到这方法实例
                ctmethod2.insertAt(20,"System.out.println( product.toString());\n" +
                        "product.setProductName(\"平板\"); \n" +
                        "System.out.println( product.toString()); \n");
                ctmethod2.insertAt(23,"\n product = new com.bank.study.pojo.Product(Integer.valueOf(2),\"电脑\",Integer.valueOf(2),Double.valueOf(8800D)); \n"
                        +"System.out.println( product.toString());\n");
                System.out.println( "444444444444444444");
                return ctclass.toBytecode();
            } catch (Exception e) {
                System.out.println(e.getMessage());
                e.printStackTrace();
            }
        }
        return null;

    }
}
